package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"hound-sys/cache"
	"hound-sys/models"
	"hound-sys/pkg"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	var data models.User

	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"smg":  "字段不能为空",
		})
		return
	}

	redis_add_key := "add_key" + username
	errcount, _ := cache.Rdb.Get(cache.Ctx, redis_add_key).Int()

	if errcount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"smg":  "密码错误三次，禁止登录",
		})
		return
	}

	if err := models.DB.Where("username = ?", username).Find(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"smg":  "用户不存在",
		})
		return
	}

	if data.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"smg":  "用户或密码错误",
		})
		return
	}

	if data.Password != pkg.MD5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_add_key)
		if errcount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_add_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"smg":  "密码错误三次以上，请两个小时或再试",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"smg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"smg":  "登录成功",
		"data": data,
	})
	return
}
func Ass(c *gin.Context) {

	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))

	data := models.UserRole{
		Uid: uid,
		Rid: rid,
	}

	if err := models.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"smg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"smg":  "添加成功",
		"data": data,
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.PostForm("page"))
	size, _ := strconv.Atoi(c.PostForm("size"))
	offset := (page - 1) * size

	var data []models.User

	redis_list_key := "list_key" + strconv.Itoa(page)
	errount, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if errount == "" {
		models.DB.Offset(offset).Limit(size).Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(errount), &data)
	}

	var total int64
	models.DB.Model(&models.User{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"smg":   "成功",
		"data":  data,
		"total": total,
	})
	return
}
